//
//  MLSegmentBar.m
//  MLSegmentBar
//
//  Created by dreamforstar on 2018/4/21.
//  Copyright © 2018年 com.jiankeyan. All rights reserved.
//

#import "MLSegmentBar.h"

@interface MLSegmentBar ()
{
    /**上一次点击的button*/
    UIButton *_lastButton;
}
/**添加按钮数据*/
@property (nonatomic,strong) NSMutableArray <UIButton *> *itemBtns;
/** 内容承载视图*/
@property (nonatomic, strong) UIScrollView *contentView;
/** 指示器*/
@property (nonatomic, strong) UIView *indicatorView;
/** 配置*/
@property (nonatomic, strong) MLSegmentBarConfig *config;
@end
@implementation MLSegmentBar

-(NSMutableArray<UIButton *> *)itemBtns {
    if (!_itemBtns) {
        _itemBtns = [NSMutableArray array];
        
    }
    return _itemBtns;
}
-(UIScrollView *)contentView {
    if (!_contentView) {
        UIScrollView * contentView = [[UIScrollView alloc] init];
        contentView.showsHorizontalScrollIndicator = NO;
        [self addSubview:contentView];
        _contentView = contentView;
        
    }
    return _contentView;
}

-(UIView *)indicatorView {
    if (!_indicatorView) {
        CGFloat indicatorHeight = self.config.indactorHeight;
        UIView * indicatorView = [[UIView alloc] initWithFrame:CGRectMake(0, self.height - indicatorHeight , 0, indicatorHeight)];
        indicatorView.backgroundColor = self.config.indactorColor;
        [self.contentView addSubview:indicatorView];
        _indicatorView = indicatorView;
    }
    return _indicatorView;
}


-(MLSegmentBarConfig *)config {
    if (!_config) {
        _config = [MLSegmentBarConfig defaultConfig];
    }
    return _config;
}
-(instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = self.config.segmentBarBackColor;
    }
    return self;
}
+(instancetype)segmentBarWithFrame:(CGRect)frame {
    MLSegmentBar *segmentBar = [[MLSegmentBar alloc] initWithFrame:frame];
    return segmentBar;
}
-(void)updateWithConfig:(void (^)(MLSegmentBarConfig *))configBlock {
    if (configBlock) {
        configBlock(self.config);
    }
        self.backgroundColor = self.config.segmentBarBackColor;
        for (UIButton *btn in self.itemBtns) {
            [btn setTitleColor:self.config.nomalColor forState:UIControlStateNormal];
            [btn setTitleColor:self.config.selectColor forState:UIControlStateSelected];
            btn.titleLabel.font = self.config.titleFont;
        }
    
    // 指示器
    self.indicatorView.backgroundColor = self.config.indactorColor;
    self.indicatorView.height = self.config.indactorHeight;
    [self setNeedsLayout];
    [self layoutIfNeeded];
        
    
}

-(void)setItems:(NSArray<NSString *> *)items {
/**重写数据源的set方法,过滤数据*/
    _items = items;
  // 删除之前添加过的组件
    [self.itemBtns  makeObjectsPerformSelector:@selector(removeFromSuperview)];
    self.itemBtns = nil;
    
    //根据数据源创建button
    for (NSString *item in items) {
        UIButton *button = [[UIButton alloc]init];
        button.tag = self.itemBtns.count;
        [button addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchDown];
        [button setTitleColor:self.config.nomalColor forState:UIControlStateNormal];
        [button setTitleColor:self.config.selectColor forState:UIControlStateSelected];
        button.titleLabel.font = self.config.titleFont;
        [button setTitle:item forState:UIControlStateNormal];
        [self.contentView addSubview:button];
        [self.itemBtns addObject:button];
        
        
    }
}
-(void)setSelectIndex:(NSInteger)selectIndex {
    if (self.items.count ==0 || selectIndex < 0 || selectIndex > self.items.count - 1) {
        return;
    }
    _selectIndex = selectIndex;
    UIButton *btn = self.itemBtns[selectIndex];
    [self btnClick:btn];
}
#pragma mark:- 私有方法
- (void)btnClick:(UIButton *)btn {
    
    if ([self.delegate respondsToSelector:@selector(segmentBar:didSelectIndex:fromIndex:)]) {
        [self.delegate segmentBar:self didSelectIndex:btn.tag fromIndex:_lastButton.tag];
    }
    _selectIndex = btn.tag;
    
    _lastButton.selected = NO;
    btn.selected = YES;
    _lastButton = btn;
    
    CGFloat indicatorExtWidth = self.config.indactorExtWidth;
    [UIView animateWithDuration:0.2 animations:^{
        self.indicatorView.width = btn.width + indicatorExtWidth * 2;
        self.indicatorView.centerX = btn.centerX;
    } ];
    
    CGFloat scrollX = btn.centerX  - self.contentView.width * 0.5;
    
    if (scrollX < 0) {
        scrollX = 0;
    }
    
    if (scrollX > self.contentView.contentSize.width - self.contentView.width) {
        scrollX = self.contentView.contentSize.width - self.contentView.width;
    }
    [self.contentView setContentOffset:CGPointMake(scrollX, 0) animated:YES];
    
    
}

-(void)layoutSubviews {
    [super layoutSubviews];
    self.contentView.frame = self.bounds;
    
    //计算间距
    CGFloat totalBtnWidth = 0;
    for (UIButton *button in self.itemBtns) {
        [button sizeToFit];
        totalBtnWidth += button.width;
    }
    
    CGFloat caculateMargin = (self.width - totalBtnWidth) / (self.items.count + 1)
    ;
    CGFloat minMargin = 20;
    if (caculateMargin < minMargin) {
        caculateMargin = minMargin;
    }
    
    CGFloat lastX = caculateMargin;
    
    
    for (UIButton *button  in self.itemBtns) {
        [button sizeToFit];
        button.y = 0;
        button.x = lastX;
        button.height = self.height - self.indicatorView.height - 1;
        lastX  += button.width + caculateMargin;
        
    }
    
    self.contentView.contentSize = CGSizeMake(lastX, 0);
    if (self.itemBtns.count == 0) {
        return;
    }
    UIButton *btn = self.itemBtns[self.selectIndex];
    self.indicatorView.width = btn.width + 10;
    self.indicatorView.centerX = btn.centerX;
    self.indicatorView.height = self.config.indactorHeight;
    self.indicatorView.y = self.height - self.indicatorView.height;
    

}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
